package com.lyx.es.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @author LiuYunXin
 * @create 2022-05-22-22:57
 */
public class ES_Doc_Insert_Batch {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 批量添加数据
        String index = "user";
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(new IndexRequest().index(index).id("1001").source(XContentType.JSON,"name","zhangsan1","age",30,"sex","男"));
        bulkRequest.add(new IndexRequest().index(index).id("1002").source(XContentType.JSON,"name","zhangsan2","age",40,"sex","女"));
        bulkRequest.add(new IndexRequest().index(index).id("1003").source(XContentType.JSON,"name","zhangsan3","age",50,"sex","男"));
        bulkRequest.add(new IndexRequest().index(index).id("1004").source(XContentType.JSON,"name","lisi1","age",30,"sex","男"));
        bulkRequest.add(new IndexRequest().index(index).id("1005").source(XContentType.JSON,"name","lisi2","age",40,"sex","女"));
        bulkRequest.add(new IndexRequest().index(index).id("1006").source(XContentType.JSON,"name","wangwu","age",30,"sex","男"));
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(response.getItems());
        restHighLevelClient.close();
    }
}
